package com.simple.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.simple.common.constant.ProductConstant;
import com.simple.common.to.SkuHasStockTo;
import com.simple.common.to.SkuReductionTo;
import com.simple.common.to.SpuBoundTo;
import com.simple.common.to.es.AttrsEsModel;
import com.simple.common.to.es.SkuEsModel;
import com.simple.common.utils.R;
import com.simple.gulimall.product.entity.*;
import com.simple.gulimall.product.feign.CouponFeignService;
import com.simple.gulimall.product.feign.SearchFeignService;
import com.simple.gulimall.product.feign.WareFeignService;
import com.simple.gulimall.product.service.*;
import com.simple.gulimall.product.vo.spu.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.simple.common.utils.PageUtils;
import com.simple.common.utils.Query;

import com.simple.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Resource
    SpuInfoDescService spuInfoDescService;
    @Resource
    SpuImagesService spuImagesService;
    @Resource
    ProductAttrValueService attrValueService;
    @Resource
    AttrService attrService;
    @Resource
    SkuInfoService skuInfoService;
    @Resource
    SkuImagesService skuImagesService;
    @Resource
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Resource
    CouponFeignService couponFeignService;
    @Resource
    BrandService brandService;
    @Resource
    CategoryService categoryService;
    @Resource
    WareFeignService wareFeignService;
    @Resource
    SearchFeignService searchFeignService;
    @Resource
    SpuInfoService spuInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    //TODO 处理保存失败的情况需要完善
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1、保存Spu基本信息            pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,spuInfoEntity);
        this.saveBaseSpuInfo(spuInfoEntity);

        Long spuId = spuInfoEntity.getId();

        //2、保存Spu的描述图片          pms_spu_info_desc
        List<String> description = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuId);
        descEntity.setDecript(String.join(",",description));
        spuInfoDescService.saveSouInfoDesc(descEntity);

        //3、保存Spu的图片集            pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuId,images);

        //4、保存Spu的规格参数          pms_product_attr_value
        List<BaseAttrs> attrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> attrValueEntities = attrs.stream().map(attr -> {
            ProductAttrValueEntity attrValueEntity = new ProductAttrValueEntity();
            attrValueEntity.setSpuId(spuId);
            attrValueEntity.setAttrId(attr.getAttrId());
            attrValueEntity.setAttrValue(attr.getAttrValues());
            attrValueEntity.setQuickShow(attr.getShowDesc());
            String attrName = attrService.getById(attr.getAttrId()).getAttrName();
            attrValueEntity.setAttrName(attrName);
            return attrValueEntity;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttrs(attrValueEntities);
        //5、保存Spu的积分信息          sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuId);
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode()!=0){
            log.error("远程保存Spu积分信息失败！");
        }

        //6、保存Spu所对应的所有Sku信息
        List<Skus> skus = vo.getSkus();
        if (skus!=null&&skus.size()>0){
            skus.forEach(sku->{
                //6.1、sku的基本信息          pms_sku_info
                String defaultImg = "";
                for (Images image :sku.getImages()){
                    if (image.getDefaultImg() == 1){
                        defaultImg = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuId);
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();
                //6.2、sku的图片信息          pms_sku_images
                List<SkuImagesEntity> skuImagesEntities = sku.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity-> !StringUtils.isEmpty(entity.getImgUrl())).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);

                //6.3、sku的销售属性信息        pms_sku_sale_attr_value
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = sku.getAttr().stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr,skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //6.4、sku的优惠满减等信息       sms_sku_ladder、sms_sku_full_reduction、sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount()>0||skuReductionTo.getFullPrice().compareTo(new BigDecimal("0"))==1){
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r.getCode()!=0){
                        log.error("远程保存Sku优惠信息失败！");
                    }
                }

            });
        }



    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and(wrapper->{
                wrapper.eq("id",key).or().like("spu_name",key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId)&&Integer.parseInt(catelogId)!=0){
            queryWrapper.eq("catalog_id",catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId)&&Integer.parseInt(brandId)!=0){
            queryWrapper.eq("brand_id",brandId);
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)){
            queryWrapper.eq("publish_status",status);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {

        // 1、查出当前的spuId对应的所有sku信息，品牌的名字等等冗余字段
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBySpuId(spuId);
        // 查询当前sku的所有可被检索的规格属性
        // 获取所有的attrId
        List<ProductAttrValueEntity> attrValueEntities = attrValueService.baseAttrListForSpu(spuId);
        List<Long> attrIds = attrValueEntities.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        // 获取其中可被检索的attr
        List<AttrEntity> searchAttrs = attrService.selectSearchAttrs(attrIds);
        // 获取到需要用的attrsEsModel
        List<AttrsEsModel> attrs = searchAttrs.stream().map(attr -> {
            AttrsEsModel attrsEsModel = new AttrsEsModel();
            BeanUtils.copyProperties(attr, attrsEsModel);
            return attrsEsModel;
        }).collect(Collectors.toList());

        List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> hasStockMap = null;
        try {
            // 统一查询是否有库存
            String skusHasStockString = wareFeignService.getSkusHasStock(skuIds);
            // 封装数据
            Map<String, Object> map = JSON.parseObject(skusHasStockString);
            ObjectMapper objectMapper = new ObjectMapper();
            List<SkuHasStockTo> skusHasStock = objectMapper.readValue(map.get("data").toString(), new TypeReference<List<SkuHasStockTo>>() {});
            hasStockMap = skusHasStock.stream().collect(Collectors.toMap(SkuHasStockTo::getSkuId, SkuHasStockTo::getHasStock));
        }catch (Exception e){
            log.error("远程调用库存服务发生错误，错误信息:{0}",e);
        }
        // 2、封装每个sku的信息
        Map<Long, Boolean> finalHasStockMap = hasStockMap;
        List<SkuEsModel> skuEsModels = skuInfoEntities.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku,skuEsModel);
            //剩下无法拷贝的字段 skuPrice/skuImg/hasStock/hotScore/brandName/brandImg/catalogName/attrs
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            // 1、hasStock调用远程库存服务查询
            if (finalHasStockMap ==null){
                skuEsModel.setHasStock(true);
            }else {
                skuEsModel.setHasStock(finalHasStockMap.get(sku.getSkuId()));
            }

            //TODO 2、hotScore先置为0，后期可根据业务进行热度判定
            skuEsModel.setHotScore(0L);
            // brandName/brandImg/catalogName 查询
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            skuEsModel.setBrandName(brandEntity.getName());
            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            // 设置检索的属性
            skuEsModel.setAttrs(attrs);

            return skuEsModel;
        }).collect(Collectors.toList());

        //将数据发送给es进行保存 gulimall-search
        R r = searchFeignService.productStatusUp(skuEsModels);
        if (r.getCode()==0){
            //商品上架成功
            // 修改当前spu的状态
            spuInfoService.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else {
            //商品上架失败
            //TODO 重复调用？接口幂等性
        }

    }

    @Override
    public void updateSpuStatus(Long spuId, int code) {
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        spuInfoEntity.setId(spuId);
        spuInfoEntity.setPublishStatus(code);
        this.updateById(spuInfoEntity);
    }

}